package com.wetool.controller.invoicing;

import javax.validation.Valid;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PagedResourcesAssembler;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.wetool.common.commodity.CommodityResult;
import com.wetool.common.model.Message;
import com.wetool.entity.invoicing.InventoryRecord;
import com.wetool.exception.ParamCheckException;
import com.wetool.exception.invoicing.ShopNotLoginException;
import com.wetool.model.enums.OutOfStorage;
import com.wetool.model.invoicing.InventoryRecordAdd;
import com.wetool.model.invoicing.InventoryRecordModify;
import com.wetool.model.invoicing.SearchParam;
import com.wetool.service.invoicing.InventoryService;
import com.wetool.service.invoicing.StorageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

/**
 * 描述：入库控制器
 * @author lixin
 * 
 */
@RestController
@RequestMapping(value = "/storages")
@RefreshScope
@Api(description = "入库管理")
public class StorageController {
	private static final Logger logger = LogManager.getLogger(StorageController.class);

	@Autowired
	private StorageService storageService;
	
	@Autowired
	private InventoryService inventoryService;
	
	@ApiOperation(value="入库信息列表", notes="查询已登录店铺的入库列表", response = Message.class)
	@ApiImplicitParam(name = "shopId", value = "店铺id", required = true, dataType = "Long", paramType = "query", defaultValue = "1")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "page", value = "第几页", required = false, dataType = "int", paramType = "query", defaultValue = "0"),
    	@ApiImplicitParam(name = "size", value = "每页行数", required = false, dataType = "int", paramType = "query", defaultValue = "20"),
    	@ApiImplicitParam(name = "sort", value = "排序规则", required = false, dataType = "String", paramType = "query", defaultValue = "createDate,asc")
    })
	@ApiResponses(value = {
			@ApiResponse(code = 0, message = "操作成功！"),
			@ApiResponse(code = 1, message = "操作失败！"),
			@ApiResponse(code = 7, message = "未找到入库记录!"),
			@ApiResponse(code = 14,message = "店家未登录!")
	})
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public ResponseEntity<?> list(SearchParam searchParam, Pageable p, Long shopId,
			final PagedResourcesAssembler<InventoryRecord> assembler) throws Exception {
		logger.info("进入接口>入库信息列表 . 参数：店铺ID【{}】,查询参数【{}】",shopId,searchParam);
		if (shopId == null) {
			logger.debug("入库信息列表 店铺ID为空");
			throw new ShopNotLoginException();
		}
		searchParam.setShopId(shopId);
		searchParam.setOutOfStorage(OutOfStorage.STORAGE);
		Page<InventoryRecord> page = inventoryService.findAll(searchParam,p);
		logger.info("进入结束>入库信息列表 . 参数：入库分页对象【{}】",page);
		return new ResponseEntity<>(new Message<>(CommodityResult.SUCCESS, assembler.toResource(page)), HttpStatus.OK);
	}

	@ApiOperation(value="查询单个入库信息", notes="查询已登录店铺的入库信息", response = Message.class)
	@ApiImplicitParams({
		@ApiImplicitParam(name = "shopId", value = "店铺id", required = true, dataType = "Long", paramType = "query", defaultValue = "1"),
		@ApiImplicitParam(name = "id", value = "入库单Id", required = true, dataType = "Long", paramType = "path", defaultValue = "1")
		})
	@ApiResponses(value = {
			@ApiResponse(code = 0, message = "操作成功！"),
			@ApiResponse(code = 1, message = "操作失败！"),
			@ApiResponse(code = 7, message = "未找到入库记录!"),
			@ApiResponse(code = 14,message = "店家未登录!")
	})
	@RequestMapping(value = "/{id}",method = RequestMethod.GET)
	public ResponseEntity<?> getById(@PathVariable Long id,Long shopId) throws Exception{
		logger.info("进入接口>查询单个入库信息 . 参数：店铺ID【{}】,查询入库信息ID【{}】",shopId,id);
		if (shopId == null) {
			logger.debug("查询单个入库信息 店铺ID为空");
			throw new ShopNotLoginException();
		}
		Message<InventoryRecordModify> storageModify = inventoryService.findOne(id);
		logger.info("结束接口>查询单个入库信息");
		return new ResponseEntity<Object>(new Message<>(CommodityResult.SUCCESS,storageModify),HttpStatus.OK);
	}
	
	@ApiOperation(value="入库信息添加", notes="已登录店铺的添加入库信息", response = Message.class)
	@ApiResponses(value = {
			@ApiResponse(code = 0, message = "操作成功！"),
			@ApiResponse(code = 1, message = "操作失败！"),
			@ApiResponse(code = 5, message = "商品不存在！"),
			@ApiResponse(code = 9, message = "添加入库信息失败!"),
			@ApiResponse(code = 14,message = "店家未登录!")
	})
	@RequestMapping(method = RequestMethod.POST)
	public ResponseEntity<?> save(@Valid @RequestBody InventoryRecordAdd inventoryRecordAdd, BindingResult bindingResult) throws Exception {
		logger.info("进入接口>入库信息添加. 参数：入库添加对象【{}】",inventoryRecordAdd);
		if (bindingResult.hasErrors()) {
			logger.debug("入库信息修改 修改信息参数格式不正确");
			throw new ParamCheckException(bindingResult);
		}
		storageService.save(inventoryRecordAdd);
		logger.info("结束接口>入库信息修改 ");
		return new ResponseEntity<Object>(new Message<>(CommodityResult.SUCCESS), HttpStatus.OK);
	}
	
	@ApiOperation(value="引用入库记录添加", notes="已登录的店铺引用入库记录添加入库", response = Message.class)
	@ApiResponses(value = {
			@ApiResponse(code = 0, message = "操作成功！"),
			@ApiResponse(code = 1, message = "操作失败！"),
			@ApiResponse(code = 5, message = "商品不存在！"),
			@ApiResponse(code = 9, message = "添加入库信息失败!"),
			@ApiResponse(code = 14,message = "店家未登录!")
	})
	@RequestMapping(method = RequestMethod.POST)
	public ResponseEntity<?> saveStorage(@Valid @RequestBody InventoryRecordAdd inventoryRecordAdd,BindingResult bindingResult) throws Exception {
		logger.info("进入接口>入库信息添加. 参数：入库添加对象【{}】",inventoryRecordAdd);
		if (bindingResult.hasErrors()) {
			logger.debug("入库信息修改 修改信息参数格式不正确");
			throw new ParamCheckException(bindingResult);
		}
		storageService.save(inventoryRecordAdd);
		logger.info("结束接口>入库信息修改 ");
		return new ResponseEntity<Object>(new Message<>(CommodityResult.SUCCESS), HttpStatus.OK);
	}
	
	@ApiOperation(value="入库信息修改", notes="已登录店铺的修改入库信息", response = Message.class)
	@ApiImplicitParam(name = "id", value = "入库单Id", required = true, dataType = "Long", paramType = "path", defaultValue = "5")
	@ApiResponses(value = {
			@ApiResponse(code = 0, message = "操作成功！"),
			@ApiResponse(code = 1, message = "操作失败！"),
			@ApiResponse(code = 5, message = "未找到商品信息！"),
			@ApiResponse(code = 12, message = "单据已提交！"),
			@ApiResponse(code = 13, message = "修改入库信息失败！"),
			@ApiResponse(code = 14,message = "店家未登录!")
	})
	@RequestMapping(value = "/{id}", method = RequestMethod.PATCH)
	public ResponseEntity<?> update(@PathVariable Long id, @RequestBody InventoryRecordModify inventoryRecordModify,BindingResult bindingResult)
			throws Exception {
		logger.info("进入接口>入库信息修改 . 参数：入库修改对象【{}】,入库信息ID【{}】",inventoryRecordModify,id);
		if (bindingResult.hasErrors()) {
			logger.debug("入库信息修改 修改信息参数格式不正确");
			throw new ParamCheckException(bindingResult);
		}
		storageService.update(id, inventoryRecordModify);
		logger.info("结束接口>入库信息修改 ");
		return new ResponseEntity<Object>(new Message<>(CommodityResult.SUCCESS), HttpStatus.OK);
	}
	
	@ApiOperation(value="入库信息删除", notes="已登录店铺的删除入库信息", response = Message.class)
	@ApiImplicitParams({
		@ApiImplicitParam(name = "shopId", value = "店铺id", required = true, dataType = "Long", paramType = "query", defaultValue = "1"),
		@ApiImplicitParam(name = "id", value = "入库单Id", required = true, dataType = "Long", paramType = "path", defaultValue = "1")
		})
	@ApiResponses(value = {
			@ApiResponse(code = 0, message = "操作成功！"),
			@ApiResponse(code = 1, message = "操作失败！"),
			@ApiResponse(code = 5, message = "商品不存在！"),
			@ApiResponse(code = 7, message = "未找到入库记录!"),
			@ApiResponse(code = 12, message = "入库单据已提交！"),
			@ApiResponse(code = 14,message = "店家未登录!")
	})
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	public ResponseEntity<?> delete(@PathVariable Long id,Long shopId) throws Exception {
		logger.info("进入接口>入库信息删除 . 参数：入库信息ID【{}】",id);
		if (shopId == null) {
			logger.debug("入库信息删除 店铺ID为空");
			throw new ShopNotLoginException();
		}
		inventoryService.delete(id);
		logger.info("结束接口>入库信息删除 ");
		return new ResponseEntity<Object>(new Message<>(CommodityResult.SUCCESS), HttpStatus.OK);
	}
}
